import { useState, useEffect } from 'react';
import { Alert } from 'react-native';
import {ToastAPI} from '@/components/Toast'


const useCaptchaCountdown = (apiFn: (payload:any) => Promise<any>) => {
  const [countdown, setCountdown] = useState(0);
  const [isDisabled, setIsDisabled] = useState(false);
  const [verifyId,setVerifyId] = useState(null)
  // 处理获取验证码点击事件
  const handleGetCaptcha = async(phoneOrEmail:string,errorText?:string) => {
    if (!phoneOrEmail) {
      ToastAPI.warning(errorText||'请输入手机号/邮箱号')
      return;
    }
    ToastAPI.loading("发生中...", "center", -1);
    if (countdown === 0) {
      setCountdown(60);
      setIsDisabled(true);
      try {
        const res:any = await apiFn({payload:phoneOrEmail})
        ToastAPI.close()
        if(res.code===0){
          ToastAPI.success('验证码已发送') 
          setVerifyId(res.result)
          return
        }
        ToastAPI.error(res.errMsg)
      }catch(error){
        ToastAPI.close()
        ToastAPI.error(JSON.stringify(error) || "请求发生错误，请稍后重试")
      }
    }
  };

  // 倒计时逻辑
  useEffect(() => {
    if (countdown > 0) {
      const timer = setInterval(() => {
        setCountdown(countdown - 1);
      }, 1000);
      return () => clearInterval(timer);
    } else {
      setIsDisabled(false); // 倒计时结束，启用按钮
    }
  }, [countdown]);

  return {
    countdown,
    isDisabled,
    handleGetCaptcha,
    verifyId
  };
};

export default useCaptchaCountdown;
